var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');
var user = require('../db/userSql.js');
var QcloudSms = require("qcloudsms_js");
let jwt = require('jsonwebtoken');

/* GET home page. */
router.get('/', function (req, res, next) {
	res.render('index', { title: 'Express' });
});

//修改购物车数量
router.post('/api/updateNum', function (req, res, next) {

	let id = req.body.id;
	let changeNum = req.body.num;

	connection.query(`select * from goods_cart where id = ${id}`, function (error, results) {
		//原来的数量
		let num = results[0].goods_num;
		connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${changeNum}) where id = ${id}`, function (err, result) {
			res.send({
				data: {
					code: 200,
					success: true
				}
			})
		})

	})

})
//删除购物车数据
router.post('/api/deleteCart', function (req, res, next) {

	let arrId = req.body.arrId;

	for (let i = 0; i < arrId.length; i++) {
		connection.query(`delete from goods_cart where id = ${arrId[i]}`, function (error, results) {
			res.send({
				data: {
					code: 200,
					success: true,
					msg: '删除成功'
				}
			})
		})
	}
})

//查询购物车数据
router.post('/api/selectCart', function (req, res, next) {
	//token
	let token = req.headers.token;
	let tokenObj = jwt.decode(token);
	//查询用户
	connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
		//用户id
		let uId = results[0].id;
		//查询购物车
		connection.query(`select * from goods_cart where uId = ${uId}`, function (err, result) {
			res.send({
				data: {
					code: 200,
					success: true,
					data: result
				}
			})
		})
	})
})
//添加购物车数据
router.post('/api/addCart', function (req, res, next) {
	//后端接收前端的参数
	let goodsId = req.body.goodsId;
	//token
	let token = req.headers.token;
	let tokenObj = jwt.decode(token);
	//查询用户
	connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
		//用户id
		let uId = results[0].id;
		//查询商品
		connection.query(`select * from goods_list where id=${goodsId}`, function (err, result) {
			let goodsName = result[0].name;
			let goodsPrice = result[0].price;
			let goodsImgUrl = result[0].imgUrl;
			//查询当前用户在之前是否添加过本商品
			connection.query(`select * from goods_cart where uId=${uId} and goods_id=${goodsId}`, function (e, r) {
				//用户之前是添加过商品到购物车
				if (r.length > 0) {
					let num = r[0].goods_num;
					connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${parseInt(num) + 1}) where id = ${r[0].id}`, function (e, datas) {
						res.send({
							data: {
								code: 200,
								success: true,
								msg: '添加成功'
							}
						})
					})
				} else {
					//没有
					connection.query(`insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values ("${uId}","${goodsId}","${goodsName}","${goodsPrice}","1","${goodsImgUrl}")`, function () {
						res.send({
							data: {
								code: 200,
								success: true,
								msg: '添加成功'
							}
						})
					})
				}
			})
		})
	})
})
//修改密码
router.post('/api/recovery', function (req, res, next) {
	let params = {
		userTel: req.body.phone,
		userPwd: req.body.pwd
	}
	//查询用户是否存在
	connection.query(user.queryUserTel(params), function (error, results) {
		//某一条记录数id
		let id = results[0].id;
		let pwd = results[0].pwd;
		console.log(`update user set pwd = replace(pwd,${pwd},${params.userPwd}) where id = ${id}`)
		connection.query(`update user set pwd = replace(pwd,'${pwd}','${params.userPwd}') where id = ${id}`, function (err, result) {
			res.send({
				code: 200,
				data: {
					success: true,
					msg: '修改成功'
				}
			})
		})
	})
})

//查询用户是否存在
router.post('/api/selectUser', function (req, res, next) {

	let params = {
		userTel: req.body.phone
	}
	//查询用户是否存在
	connection.query(user.queryUserTel(params), function (error, results) {
		if (results.length > 0) {
			res.send({
				code: 200,
				data: {
					success: true
				}
			})
		} else {
			res.send({
				code: 0,
				data: {
					success: false,
					msg: '此用户不存在'
				}
			})
		}
	})
})
//注册
router.post('/api/register', function (req, res, next) {
	let params = {
		userTel: req.body.phone,
		userPwd: req.body.pwd
	}
	//查询用户是否存在
	connection.query(user.queryUserTel(params), function (error, results) {
		if (error) throw error;
		//用户存在
		if (results.length > 0) {
			res.send({
				code: 200,
				data: {
					success: true,
					msg: '登录成功',
					data: results[0]
				}
			})
		} else {
			//不存在，新增一条数据
			connection.query(user.inserData(params), function (err, result) {
				connection.query(user.queryUserTel(params), function (e, r) {
					res.send({
						code: 200,
						data: {
							success: true,
							msg: '登录成功',
							data: r[0]
						}
					})
				})
			})
		}
	})
})

//增加一个用户
router.post('/api/addUser', function (req, res, next) {

	let params = {
		userTel: req.body.phone
	}
	//查询用户是否存在
	connection.query(user.queryUserTel(params), function (error, results) {
		if (error) throw error;
		//用户存在
		if (results.length > 0) {
			res.send({
				code: 200,
				data: {
					success: true,
					msg: '登录成功',
					data: results[0]
				}
			})
		} else {
			//不存在，新增一条数据
			connection.query(user.inserData(params), function (err, result) {
				connection.query(user.queryUserTel(params), function (e, r) {
					res.send({
						code: 200,
						data: {
							success: true,
							msg: '登录成功',
							data: r[0]
						}
					})
				})
			})
		}
	})
})
//发送短信验证码
router.post('/api/code', function (req, res, next) {

	let tel = req.body.phone;

	// 短信应用SDK AppID
	var appid = 1400187558;  // SDK AppID是1400开头

	// 短信应用SDK AppKey
	var appkey = "dc9dc3391896235ddc2325685047edc7";

	// 需要发送短信的手机号码
	var phoneNumbers = [tel];

	// 短信模板ID，需要在短信应用中申请
	var templateId = 285590;  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

	// 签名
	var smsSign = "三人行慕课";  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

	// 实例化QcloudSms
	var qcloudsms = QcloudSms(appid, appkey);

	// 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
	function callback(err, ress, resData) {
		if (err) {
			console.log("err: ", err);
		} else {
			res.send({
				code: 200,
				data: {
					success: true,
					data: ress.req.body.params[0]
				}
			})
		}
	}

	var ssender = qcloudsms.SmsSingleSender();
	//这个变量：params 就是往手机上，发送的短信
	var params = [Math.floor(Math.random() * (9999 - 1000)) + 1000];
	ssender.sendWithParam(86, phoneNumbers[0], templateId,
		params, smsSign, "", "", callback);  // 签名参数不能为空串

})

//登录
router.post('/api/login', function (req, res, next) {
	//后端要接收前端传递过来的值
	let params = {
		userTel: req.body.userTel,
		userPwd: req.body.userPwd
	};

	//查询用户手机号是否存在
	connection.query(user.queryUserTel(params), function (error, results) {
		//手机号存在 
		if (results.length > 0) {
			connection.query(user.queryUserPwd(params), function (err, result) {
				if (result.length > 0) {
					//手机号和密码都对
					res.send({
						code: 200,
						data: {
							success: true,
							msg: '登录成功',
							data: result[0]
						}
					})
				} else {
					//密码不对
					res.send({
						code: 302,
						data: {
							success: false,
							msg: '密码不正确'
						}
					})
				}
			})

		} else {
			//不存在
			res.send({
				code: 301,
				data: {
					success: false,
					msg: '手机号不存在'
				}
			})
		}
	})
})



//查询商品id的数据
router.get('/api/goods/id', function (req, res, next) {
	let id = req.query.id;
	connection.query('select * from goods_list where id=' + id + '', function (error, results) {
		if (error) throw error;
		res.json({
			code: 0,
			data: results[0]
		})
	})
})

//分类的接口
router.get('/api/goods/list', function (req, res, next) {

	res.send({
		code: 0,
		data: [
			{
				//一级
				id: 0,
				name: '推荐',
				data: [
					{
						//二级
						id: 0,
						name: '推荐',
						list: [
							//三级
							{
								id: 0,
								name: '青春小说',
								imgUrl: './images/like4.jpg'
							},
							{
								id: 1,
								name: '世界名著',
								imgUrl: './images/book9.jpg'
							},
							{
								id: 3,
								name: '悬疑推理',
								imgUrl: './images/list2.jpg'
							},
							{
								id: 4,
								name: '美食菜谱',
								imgUrl: './images/list3.jpg'
							},
							{
								id: 5,
								name: '考研',
								imgUrl: './images/list4.jpg'
							},
							{
								id: 6,
								name: '四六',
								imgUrl: './images/list5.jpg'
							}
						]
					}
				]
			},
			{
				//一级
				id: 1,
				name: '文学小说',
				data: [
					{
						//二级
						id: 0,
						name: '文学',
						list: [
							//三级
							{
								id: 0,
								name: '中国文学',
								imgUrl: './images/list6.jpg'
							},
							{
								id: 1,
								name: '外国文学',
								imgUrl: './images/book9.jpg'
							},
							{
								id: 3,
								name: '随笔散文',
								imgUrl: './images/list6.jpg'
							},
							{
								id: 4,
								name: '诗词歌赋',
								imgUrl: './images/list7.jpg'
							},

						]
					},
					{
						//二级
						id: 1,
						name: '小说',
						list: [
							//三级
							{
								id: 0,
								name: '中外小说',
								imgUrl: './images/book1.jpg'
							},
							{
								id: 1,
								name: '青春小说',
								imgUrl: './images/like4.jpg'
							},
							{
								id: 3,
								name: '世界名著',
								imgUrl: './images/book9.jpg'
							},
							{
								id: 4,
								name: '悬疑推理',
								imgUrl: './images/list2.jpg'
							},

						]
					},
				]
			},
			{
				//一级
				id: 2,
				name: '童书绘本',
				data: [
					{
						//二级
						id: 0,
						name: '童书绘本',
						list: [
							//三级
							{
								id: 0,
								name: '儿童绘本',
								imgUrl: './images/lista.jpg'
							},
							{
								id: 1,
								name: '绘本',
								imgUrl: './images/lista.jpg'
							},
							{
								id: 3,
								name: '科普百科',
								imgUrl: './images/lista.jpg'
							},
						]
					}
				]
			},
			{
				//一级
				id: 3,
				name: '人文社科',
				data: [
					{
						//二级
						id: 0,
						name: '人文社科',
						list: [
							//三级
							{
								id: 0,
								name: '社会学',
								imgUrl: './images/list9.jpg'
							},
							{
								id: 1,
								name: '语言文学',
								imgUrl: './images/list9.jpg'
							},
							{
								id: 3,
								name: '传媒出版',
								imgUrl: './images/list9.jpg'
							},
							{
								id: 4,
								name: '历史人文',
								imgUrl: './images/list9.jpg'
							},
							{
								id: 5,
								name: '自然科学',
								imgUrl: './images/list9.jpg'
							}
						]
					}
				]
			},
			{
				//一级
				id: 4,
				name: '漫画书籍',
				data: [
					{
						//二级
						id: 0,
						name: '漫画书籍',
						list: [
							//三级
							{
								id: 0,
								name: '流行漫画',
								imgUrl: './images/list8.jpg'
							},
							{
								id: 1,
								name: '仙侠科幻',
								imgUrl: './images/list8.jpg'
							},
							{
								id: 3,
								name: '幽默治愈',
								imgUrl: './images/list8.jpg'
							},
							{
								id: 4,
								name: '青春言情',
								imgUrl: './images/list8.jpg'
							},
							{
								id: 5,
								name: '卡通经典',
								imgUrl: './images/list8.jpg'
							},
							{
								id: 6,
								name: '益智学习',
								imgUrl: './images/list8.jpg'
							}
							,
							{
								id: 7,
								name: '日本经典',
								imgUrl: './images/list8.jpg'
							},
							{
								id: 8,
								name: '少儿漫画',
								imgUrl: './images/list8.jpg'
							}
						]
					}
				]
			},
			{
				//一级
				id: 5,
				name: '考研考试',
				data: [
					{
						//二级
						id: 0,
						name: '大学考试',
						list: [
							//三级
							{
								id: 0,
								name: '考研',
								imgUrl: './images/list4.jpg'
							},
							{
								id: 1,
								name: '四六',
								imgUrl: './images/list5.jpg'
							},
							{
								id: 3,
								name: '大学教材',
								imgUrl: './images/list5.jpg'
							},
						]
					},
					{
						//二级
						id: 0,
						name: '成人考试',
						list: [
							//三级
							{
								id: 0,
								name: '经济类考试',
								imgUrl: './images/list5.jpg'
							},
							{
								id: 1,
								name: '建筑类考试',
								imgUrl: './images/list5.jpg'
							},
						]
					},
				]
			},
			{
				//一级
				id: 5,
				name: '生活休闲',
				data: [
					{
						//二级
						id: 0,
						name: '生活百科',
						list: [
							//三级
							{
								id: 0,
								name: '美食菜谱',
								imgUrl: './images/list3.jpg'
							},
							{
								id: 1,
								name: '饮食文化',
								imgUrl: './images/list3.jpg'
							},
							{
								id: 3,
								name: '基金理财',
								imgUrl: './images/list3.jpg'
							},
						]
					},
					{
						//二级
						id: 0,
						name: '婚姻生活',
						list: [
							//三级
							{
								id: 0,
								name: '情感婚恋',
								imgUrl: './images/listb.jpg'
							},
							{
								id: 1,
								name: '家居装修',
								imgUrl: './images/listb.jpg'
							},
						]
					},
				]
			}

		]
	})

})


//查询商品数据接口
router.get('/api/goods/shopList', function (req, res, next) {
	//前端给后端的数据
	let [searchName, orderName] = Object.keys(req.query);
	let [name, order] = Object.values(req.query);

	connection.query('select * from goods_list where name like "%' + name + '%" order by ' + orderName + ' ' + order + '', function (error, results) {
		res.send({
			code: 0,
			data: results
		})
	})
})

//1.首页青春数据
router.get('/api/index_list/1/data/1', function (req, res, next) {
	res.send({
		code: 0,
		data: [
			{
				id: 1,
				type: 'adList',
				data: [
					{
						id: 1,
						imgUrl: './images/qc.jpg'
					},
				]
			},
			{
				id: 3,
				type: 'likeList',
				data: [
					{
						id: 1,
						imgUrl: './images/like1.jpg',
						name: '难哄 温以凡X桑延晋江青春言情小说书籍',
						price: 45.90,
					},
					{
						id: 2,
						imgUrl: './images/like2.jpg',
						name: '至此终年 墨宝非宝2021新作 顾平生x童言都市言情小说实体书',
						price: 50.99,
					},
					{
						id: 3,
						imgUrl: './images/like3.jpg',
						name: '奶油味暗恋上下两册 竹已著青春文学现代言情校园爱情小说畅销书籍正版包邮',
						price: 65.00,
					},
					{
						id: 4,
						imgUrl: './images/like4.jpg',
						name: '纸飞机 潭石著 长佩文学城青春小说畅销书籍校园故事 正版',
						price: 25.99,
					}
				]
			}

		]
	})
})
//2.首页文学的数据
router.get('/api/index_list/2/data/1', function (req, res, next) {
	res.send({
		code: 0,
		data: [
			{
				id: 1,
				type: 'adList',
				data: [
					{
						id: 1,
						imgUrl: './images/jd.jpg'
					},
				]
			},
			{
				id: 2,
				type: 'likeList',
				data: [
					{
						id: 1,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 2,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 3,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					}
				]
			}

		]
	})
})
//3.首页小说的数据
router.get('/api/index_list/3/data/1', function (req, res, next) {
	res.send({
		code: 0,
		data: [
			{
				id: 1,
				type: 'adList',
				data: [
					{
						id: 1,
						imgUrl: './images/xs.jpg'
					},
				]
			},
			{
				id: 2,
				type: 'likeList',
				data: [
					{
						id: 1,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 2,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 3,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					}
				]
			}

		]
	})
})

//4.首页艺术的数据
router.get('/api/index_list/4/data/1', function (req, res, next) {
	res.send({
		code: 0,
		data: [
			{
				id: 1,
				type: 'adList',
				data: [
					{
						id: 1,
						imgUrl: './images/ys.jpg'
					},
				]
			},
			{
				id: 2,
				type: 'likeList',
				data: [
					{
						id: 1,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 2,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 3,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					}
				]
			}

		]
	})
})

//5.首页动漫的数据
router.get('/api/index_list/5/data/1', function (req, res, next) {
	res.send({
		code: 0,
		data: [
			{
				id: 1,
				type: 'adList',
				data: [
					{
						id: 1,
						imgUrl: './images/mh.jpg'
					},
				]
			},
			{
				id: 2,
				type: 'likeList',
				data: [
					{
						id: 1,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 2,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					},
					{
						id: 3,
						imgUrl: './images/like.jpg',
						name: '世界经典名著',
						price: 29,
					}
				]
			}

		]
	})
})


//首页推荐的数据
router.get('/api/index_list/0/data/1', function (req, res, next) {
	res.send({
		code: 0,
		data: {
			topBar: [
				{ id: 0, label: '推荐' },
				{ id: 1, label: '青春' },
				{ id: 2, label: '文学' },
				{ id: 3, label: '小说' },
				{ id: 4, label: '艺术' },
				{ id: 5, label: '动漫' },
				{ id: 6, label: '旅游' },
			],
			data: [
				//这是swiper
				{
					id: 0,
					type: 'swiperList',
					data: [
						{ id: 0, imgUrl: './images/swiper1.jpg' },
						{ id: 1, imgUrl: './images/swiper2.jpg' },
						{ id: 3, imgUrl: './images/swiper3.jpg' }
					]
				},
				// //这是icons
				// {
				//   id: 1,
				//   type: 'iconsList',
				//   data: [
				//     {
				//       id: 1,
				//       title: '销量排行',
				//       imgUrl: './images/icons1.png'
				//     },
				//     {
				//       id: 2,
				//       title: '热门推荐',
				//       imgUrl: './images/icons2.png'
				//     },
				//     {
				//       id: 3,
				//       title: '精选图书',
				//       imgUrl: './images/icons3.png'
				//     },
				//     {
				//       id: 4,
				//       title: '会员福利',
				//       imgUrl: './images/icons4.png'
				//     },
				//     {
				//       id: 4,
				//       title: '会员福利',
				//       imgUrl: './images/icons5.png'
				//     },
				//   ]
				// },
				//畅销图书
				{
					id: 3,
					type: 'recommendList',
					data: [
						{
							id: 1,
							name: "何以笙箫默",
							content: "一部关于制作与等待的爱情小说",
							price: "28.8",
							imgUrl: "./images/recommend2.jpg",
						},
						{
							id: 2,
							name: "何以笙箫默",
							content: "一部关于制作与等待的爱情小说",
							price: "19.9",
							imgUrl: "./images/recommend2.jpg",
						},
					]
				},
				//猜你喜欢
				{
					id: 4,
					type: 'likeList',
					data: [
						{
							id: 1,
							imgUrl: './images/book1.jpg',
							name: '哈姆雷特正版书-莎士比亚悲剧集',
							price: 28.90,
						},
						{
							id: 2,
							imgUrl: './images/book2.jpg',
							name: '何以笙箫默-一部关于制作与等待的爱情小说',
							price: 19.90,
						},
						{
							id: 3,
							imgUrl: './images/book3.jpg',
							name: '呼啸山庄-外国现代经典文学',
							price: 30.90,
						},
						{
							id: 4,
							imgUrl: './images/book4.jpg',
							name: '茶花女-法国小说原著现当代外国世界名著',
							price: 40.90,
						},
						{
							id: 5,
							imgUrl: './images/book5.jpg',
							name: '红与黑-司汤达原著经典世界文学名著',
							price: 25.60,
						},
						{
							id: 6,
							imgUrl: './images/book6.jpg',
							name: '巴黎圣母院-世界文学名著',
							price: 25.60,
						},
					]
				}

			]
		}
	})
});

module.exports = router;
